{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "from pytorch_metric_learning.distances import LpDistance, CosineSimilarity, DotProductSimilarity\n",
    "from pytorch_metric_learning.losses import NTXentLoss, SupConLoss\n",
    "from pytorch_metric_learning.reducers import AvgNonZeroReducer, PerAnchorReducer\n",
    "from pytorch_metric_learning.utils import common_functions as c_f\n",
    "\n",
    "import os\n",
    "\n",
    "TEST_DEVICE = torch.device(os.environ.get(\"TEST_DEVICE\", \"cuda\"))\n",
    "\n",
    "dtypes_from_environ = os.environ.get(\"TEST_DTYPES\", \"float16,float32,float64\").split(\n",
    "    \",\"\n",
    ")\n",
    "TEST_DTYPES = [getattr(torch, x) for x in dtypes_from_environ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[ 0.4062, -0.8911, -1.2310,  0.9125, -1.5183,  0.8626,  1.1209,  0.9120,\n",
      "         -0.0450,  0.0820, -0.7680, -0.7216,  0.3709],\n",
      "        [ 0.9646,  0.7243,  0.1546, -0.4211, -0.1617, -1.6971, -0.2457,  1.7273,\n",
      "          0.3448, -2.0385, -0.0436,  0.1245,  0.9833],\n",
      "        [-0.8108, -1.5350, -0.0390,  1.8846, -1.1494, -1.5596, -1.0899, -2.0461,\n",
      "          1.4187, -0.7099,  0.0949,  1.2315,  0.5286],\n",
      "        [ 0.4251,  0.9468,  0.0475, -0.5334, -2.0651,  0.8345,  0.5650, -0.7073,\n",
      "         -0.8625, -0.7808, -1.4542, -0.5173,  0.0982],\n",
      "        [-2.8500,  0.5913, -2.4303, -0.1210, -1.3269, -2.2679, -0.3523,  0.0950,\n",
      "          0.2033, -0.4219, -0.9945, -0.4709, -2.3443],\n",
      "        [ 0.6186, -0.0486, -1.3054, -1.8398, -1.3805,  1.3874,  0.0744, -0.9763,\n",
      "         -0.7732,  0.7235,  1.2201,  0.3298, -0.0446]])\n"
     ]
    }
   ],
   "source": [
    "# embeddings\n",
    "batch_size = 6\n",
    "hidden_dim = 13\n",
    "\n",
    "embeddings = torch.randn((batch_size, hidden_dim))\n",
    "print(embeddings)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# labels\n",
    "labels = torch.LongTensor([0, 0, 0, 1, 1, 2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NTXentLoss(\n",
      "  (distance): CosineSimilarity()\n",
      "  (reducer): MeanReducer()\n",
      ")\n"
     ]
    }
   ],
   "source": [
    "# loss_funcA\n",
    "temperature = 0.1\n",
    "\n",
    "loss_funcA = NTXentLoss(temperature=temperature, )\n",
    "print(loss_funcA)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(2.9303)\n"
     ]
    }
   ],
   "source": [
    "# 计算 loss A\n",
    "loss_A = loss_funcA(embeddings, labels)\n",
    "print(loss_A)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(0.5735) tensor(62.2873) tensor(4.6878)\n",
      "tensor(0.5758) tensor(62.2896) tensor(4.6838)\n",
      "tensor(0.5735) tensor(3.0223) tensor(1.6621)\n",
      "tensor(0.7222) tensor(3.1710) tensor(1.4795)\n",
      "tensor(0.5758) tensor(9.7488) tensor(2.8291)\n",
      "tensor(0.7222) tensor(9.8952) tensor(2.6175)\n",
      "tensor(2.3383) tensor(88.9860) tensor(3.6390)\n",
      "tensor(2.3383) tensor(14.7796) tensor(1.8438)\n",
      "total_lossA:  tensor(2.9303)\n"
     ]
    }
   ],
   "source": [
    "# 复现计算过程\n",
    "# 注意：distance默认是 CosineSimilarity()\n",
    "\n",
    "pos_pairs = [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1), (3, 4), (4, 3)]\n",
    "neg_pairs = [\n",
    "    (0, 3), (0, 4), (0, 5),\n",
    "    (1, 3), (1, 4), (1, 5),\n",
    "    (2, 3), (2, 4), (2, 5),\n",
    "    (3, 0), (3, 1), (3, 2), (3, 5),\n",
    "    (4, 0), (4, 1), (4, 2), (4, 5),\n",
    "    (5, 0), (5, 1), (5, 2), (5, 3), (5, 4),\n",
    "]\n",
    "\n",
    "total_lossA = 0\n",
    "\n",
    "for a1, p in pos_pairs:\n",
    "    # a1: anchor;\n",
    "    # p: positive instance\n",
    "    \n",
    "    anchor, positive = embeddings[a1], embeddings[p]\n",
    "    numeratorA = torch.exp(torch.matmul(anchor, positive) / (temperature * torch.norm(anchor) * torch.norm(positive)))\n",
    "    \n",
    "    denominatorA = numeratorA.clone()\n",
    "    \n",
    "    for a2, n in pos_pairs + neg_pairs:\n",
    "        # n: negative instance\n",
    "        \n",
    "        if a2 == a1:\n",
    "            negative = embeddings[n]\n",
    "            curr_denomD = torch.exp(\n",
    "                torch.matmul(anchor, negative) / (temperature * torch.norm(anchor) * torch.norm(negative))\n",
    "            )\n",
    "            if (a2, n) not in pos_pairs:\n",
    "                denominatorA += curr_denomD\n",
    "        else:\n",
    "            continue\n",
    "    \n",
    "    print(numeratorA, denominatorA, - torch.log(numeratorA / denominatorA))\n",
    "    curr_lossA = -torch.log(numeratorA / denominatorA)\n",
    "    total_lossA += curr_lossA\n",
    "\n",
    "total_lossA /= len(pos_pairs)\n",
    "\n",
    "print(\"total_lossA: \", total_lossA)\n",
    "\n",
    "rtol = 1e-4\n",
    "assert torch.isclose(loss_A, total_lossA, rtol=rtol)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
